const db = wx.cloud.database();
const todos = db.collection('todos');
const globalData = getApp().globalData;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tasks: [],
    isLoading: true,
    isShowActionSheet: false,
    actions: [
      { id: 'done', name: '标记为已完成', color: '#67C23A', },
      { id: 'in-progress', name: '标记为进行中', color: '#409EFF', },
      { id: 'abandoned', name: '废弃', color: '#909399', },
      { id: 'delete', name: '删除', color: '#F56C6C', },
    ],
  },

  page: {
    status: 'ok', // ok, nomore
    size: 20,
  },

  // 长按选中的任务
  taskOfLongPress: null,

  onLongPress(e) {
    this.taskOfLongPress = e.target.dataset.task;
    this.setData({
      isShowActionSheet: true,
    });
  },

  async onSelectAction(e) {
    if (e.detail.id === 'delete') {
      globalData.showLoading('删除中...');
      const res = await todos.doc(this.taskOfLongPress._id).remove()
      if (res.stats.removed === 1) {
        this.setData({
          tasks: this.data.tasks.filter(v => v._id !== this.taskOfLongPress._id),
        });
        globalData.Toast.success('删除成功')

        // 删除云存储图片
        if (this.taskOfLongPress.images && this.taskOfLongPress.images.length > 0) {
          await wx.cloud.deleteFile({
            fileList: this.taskOfLongPress.images,
          });
        }
        // /删除云存储图片

      } else {
        globalData.Toast.fail('删除失败，请稍后重试')
      }
    } else {
      if (this.taskOfLongPress.status === e.detail.id) {
        globalData.Toast.success('标记成功');
        return;
      }
      const res = await todos.doc(this.taskOfLongPress._id).update({
        data: {
          status: e.detail.id,
        },
      });
      if (res.stats.updated) {
        const index = this.data.tasks.findIndex(v => v._id === this.taskOfLongPress._id);
        const status = e.detail.id;
        const statusText = ({ 'in-progress': '进行中', 'done': '已完成', 'abandoned': '已废弃' }[status]);
        const statusTextColor = ({ 'in-progress': '#409EFF', 'done': '#67C23A', 'abandoned': '#909399' }[status]);
        this.setData({
          [`tasks[${index}].status`]: status,
          [`tasks[${index}].statusText`]: statusText,
          [`tasks[${index}].statusTextColor`]: statusTextColor,
        });
        globalData.Toast.success('标记成功');
      }
    }
  },

  onCloseActionSheet() {
    this.setData({
      isShowActionSheet: false,
    });
  },

  onCancelActionSheet() {
    this.setData({
      isShowActionSheet: false,
    });
  },

  async loadTasks(skip = 0) {
    if (this.page.status !== 'ok') {
      throw new Error(this.page.status);
    }
    this.setData({
      isLoading: true,
    });
    globalData.showLoading();
    const res = await todos.skip(skip).get();
    if (res.data.length < this.page.size) {
      this.page.status = 'nomore';
    }
    this.setData({
      tasks: this.data.tasks.concat(res.data.map(v => {
        v.statusText = ({ 'in-progress': '进行中', 'done': '已完成', 'abandoned': '已废弃' }[v.status]);
        v.statusTextColor = ({ 'in-progress': '#409EFF', 'done': '#67C23A', 'abandoned': '#909399' }[v.status]);
        return v;
      })),
    });
    globalData.hideLoading();
    this.setData({
      isLoading: false,
    });
  },

  goAddTask() {
    wx.navigateTo({
      url: '../add/index',
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.loadTasks();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.page.status = 'ok';
    this.loadTasks(this.data.tasks.length);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    this.page.status = 'ok';
    this.data.tasks.splice(0);
    await this.loadTasks();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  async onReachBottom() {
    try {
      await this.loadTasks(this.data.tasks.length);
    } catch (err) {
      if (err.message === 'nomore') {
        globalData.Toast('没有更多了');
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
});